<?php


namespace PKApp\Topic;


use PKApp\Topic\Classes\TraitTopic;
use PKCommon\Controller\AdminController;
use PKFrame\DataHandler\MatchHelper;
use PKFrame\DataHandler\Numbers;

class AdminSetTopic extends AdminController
{
    use TraitTopic;

    public function Main()
    {
        $this->assign([
            'id' => Numbers::To(request()->get('id'))
        ])->fetch('topic_set');
    }

    private function _modelOfTopic(): array
    {
        $params = $this->checkModel(['seoTitle', 'seoKeyword', 'seoDescription', 'banner', 'image', 'content']);
        $params = array_merge($params, [
            'title' => $this->checkPostFieldIsEmpty('title', 'Empty_topicTitle'),
            'fileTpl' => $this->checkPostFieldIsEmpty('fileTpl', 'Empty_topicFileTpl'),
            'fileHtml' => $this->checkPostFieldIsEmpty('fileHtml', 'Empty_topicFileHtml'),
            'siteId' => $this->loginUser()->SiteId,
        ]);
        if (empty($params['seoTitle'])) {
            $params['seoTitle'] = $params['title'];
        }
        if (empty($params['seoDescription'])) {
            if (empty($params['content'])) {
                $params['seoDescription'] = $params['title'];
            } else {
                MatchHelper::GetPTagInHTMLCode($params['content'], $output);
                $params['seoDescription'] = strip_tags($output[0]);
            }
        }
        return $params;
    }

    public function ApiByCreate()
    {
        $params = $this->_modelOfTopic();
        $params['createTime'] = TIMESTAMP;
        $this->serviceOfTopic()->Add($params);
        $this->json();
    }

    public function ApiByChange()
    {
        $params = $this->_modelOfTopic();
        $id = $this->postId('id', 'Empty_TopicId');
        $this->serviceOfTopic()->UpdateById($id, $params);
        $this->serviceOfTopicContent()->Update(['topicId' => $id], ['topicTitle' => $params['title']]);
        $this->json();
    }

    public function ApiByDel()
    {
        $id = $this->postId('id', 'Empty_TopicId');
        $this->serviceOfTopic()->HideById($id);
        $this->json();
    }
}